package com.example.sunflowers.adapters

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.navigation.findNavController
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView.ViewHolder
import cn.trans88.taxiappkotlin.ext.logd
import cn.trans88.taxiappkotlin.ext.loge
import com.example.sunflowers.data.db.Plant
import com.example.sunflowers.databinding.ListItemPlantBinding
import com.example.sunflowers.ui.HomeViewPagerFragmentDirections

/**
 *
 * @Author： LJH
 * @Time： 2024/1/29
 * @description：
 */
class PlantAdapter:ListAdapter<Plant,ViewHolder>(PlantDiffCallback()) {

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
            return PlantViewHolder(
                ListItemPlantBinding.inflate(
                    LayoutInflater.from(parent.context),
                    parent,
                    false
                )
            )
    }

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        val plant = getItem(position)
        (holder as PlantViewHolder).bind(plant)
    }

    class PlantViewHolder(
        private val binding:ListItemPlantBinding
    ):ViewHolder(binding.root){

        init {
            binding.setClickListener {
                binding.plant?.let { plant ->
                    navigateToPlant(plant,it)
                }
            }
        }

        private fun navigateToPlant(plant: Plant,view: View){
            val direction = HomeViewPagerFragmentDirections.actionHomeViewPagerFragmentToPlantDetailFragment(
                plant.plantId
            )
            view.findNavController().navigate(direction)
        }

        fun bind(item:Plant){
            "item ---> :$item".logd()
            binding.apply {
                plant = item
                executePendingBindings()
            }
        }
    }
}

private class PlantDiffCallback:DiffUtil.ItemCallback<Plant>(){
    override fun areItemsTheSame(oldItem: Plant, newItem: Plant): Boolean {
        return oldItem.plantId == newItem.plantId
    }

    override fun areContentsTheSame(oldItem: Plant, newItem: Plant): Boolean {
        return oldItem == newItem
    }
}